//
//  YEventViewController.m
//  shijianpinggu
//
//  Created by apple on 2016/12/28.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "YEventViewController.h"
#import "YEventTableViewCell.h"
#import "YEventListTableViewController.h"
#import "eventModel.h"
#import "YZhangdianxinxiViewController.h"

@interface YEventViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *eventIma;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *eventButton;
@property (weak, nonatomic) IBOutlet UIButton *dangerButton;
- (IBAction)eventButtonAction:(UIButton *)sender;
- (IBAction)dangerButtonAction:(UIButton *)sender;

@property (weak, nonatomic) IBOutlet UILabel *eventNumber;
@property (weak, nonatomic) IBOutlet UILabel *dangerNumber;

@property(nonatomic,strong)NSMutableArray *eventAr;
@property(nonatomic,strong)NSMutableArray *dangerAr;
@property(nonatomic,strong)NSMutableArray *dataAr;

@property(nonatomic,assign)NSInteger eventNum;
@property(nonatomic,assign)NSInteger dangerNum;

@property(nonatomic,strong)NSString *typeTwo;
- (IBAction)zhandianxinxiButtonAction:(UIButton *)sender;

@end

@implementation YEventViewController
-(NSMutableArray *)eventAr{
    if(_eventAr==nil){
        self.eventAr = [[NSMutableArray alloc] init];
    }
    return _eventAr;
}
-(NSMutableArray *)dangerAr{
    if(_dangerAr==nil){
        self.dangerAr = [[NSMutableArray alloc] init];
    }
    return _dangerAr;
}
-(NSMutableArray *)dataAr{
    if(_dataAr==nil){
        self.dataAr = [[NSMutableArray alloc] init];
    }
    return _dataAr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.delegate = self;
    self.tableView.dataSource =self;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone; 
    [self.tableView registerNib:[UINib nibWithNibName:@"YEventTableViewCell" bundle:nil] forCellReuseIdentifier:@"eventCell"];
    
    // 设置导航栏背景
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"jiance_top"] forBarMetrics:UIBarMetricsDefault];
    //去掉返回按钮上的文字
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
    // 设置状态栏
    [UIApplication sharedApplication].statusBarStyle = UIBarStyleBlackOpaque;
    
    //    隐藏UINavigationController
    //self.navigationController.navigationBarHidden = YES;
    self.navigationItem.title = @"监测结果";
    
    [self buttonUI:self.eventButton];
    [self buttonUI:self.dangerButton];
    [self buttonUI:self.eventNumber];
    [self buttonUI:self.dangerNumber];
    self.eventNumber.hidden = YES;
    self.typeTwo = @"shijian";
    self.dangerNumber.hidden = YES;
    
    [self loadDataFormUrl];
    
    
}
//请求数据
-(void)loadDataFormUrl{
    
    
    NSDictionary *parameter = @{@"virtual_group_id":self.webid,@"WebUrl":self.weburl};
    
        NSLog(@"%@",parameter);
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:@"http://wangan.ldynet.cn/index.php/IndexApp/Test_report" parameters:parameter constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        if (dic) {
            
        
        NSLog(@"%@", dic);
        NSArray *evAr = dic[@"event"];
        
        NSMutableArray *eventArray = [[NSMutableArray alloc] init];
        for (int i=0; i<[evAr count]; i++) {
            for (id f in [evAr objectAtIndex:i]) {
                if(![f isEqualToString:@"dangernum"]){
                [eventArray insertObject:[[evAr objectAtIndex:i] valueForKey:f] atIndex:0];
                }else{
                    self.dangerNum = [[[evAr objectAtIndex:i] valueForKey:f] integerValue];
                    if (self.dangerNum > 0) {
                        self.dangerNumber.hidden = NO;
                        self.dangerNumber.text = [NSString stringWithFormat:@"%ld",(long)self.dangerNum];
                    }else{
                        self.dangerNumber.hidden = YES;
                    }
                    
                }
            }
        }
        
        for (NSDictionary *dic in eventArray) {
            eventModel *emodel = [[eventModel alloc] init];
            [emodel setValuesForKeysWithDictionary:dic];
            [self.eventAr insertObject:emodel atIndex:0];
        }
        
        NSArray *daAr = dic[@"danger"];
        NSMutableArray *dangerArray = [[NSMutableArray alloc] init];
        for (int i=0; i<[daAr count]; i++) {
            for (id f in [daAr objectAtIndex:i]) {
                if(![f isEqualToString:@"eventnum"]){
                    [dangerArray insertObject:[[daAr objectAtIndex:i] valueForKey:f] atIndex:0];
                }else{
                    self.eventNum = [[[daAr objectAtIndex:i] valueForKey:f] integerValue];
                    if (self.eventNum > 0) {
                        self.eventNumber.hidden = NO;
                        self.eventNumber.text = [NSString stringWithFormat:@"%ld",(long)self.eventNum];
                    }else{
                        self.eventNumber.hidden = YES;
                    }

                    
                }
            }
        }
        
        for (NSDictionary *dic in dangerArray) {
            eventModel *emodel = [[eventModel alloc] init];
            [emodel setValuesForKeysWithDictionary:dic];
            
            [self.dangerAr insertObject:emodel atIndex:0];
        }
        
        self.dataAr = self.eventAr;
        [self.tableView reloadData];
        //        冒泡排序
        for(int i = 0;i < [self.dataAr count]-1;i++){
            for(int j = i+1;j<[self.dataAr count];j++){
                eventModel *emodelI  = self.dataAr[i];
                eventModel *emodelJ = self.dataAr[j];
                int numi= [emodelI.total intValue];
                int numj= [emodelJ.total intValue];
                
                if(numi<numj) {
                    //交换
                    [self.dataAr exchangeObjectAtIndex:i withObjectAtIndex:j];
                    
                }
            }
        }

        [self.tableView reloadData];
        }        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 请求失败
        // [self alertWithString:@"请稍后再试"];
    }];
    
    
    
}

-(void)buttonUI:(UIView *)sender{
    //控件切圆角
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:sender.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:sender.bounds.size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
    //设置大小
    maskLayer.frame = sender.bounds;
    //设置图形样子
    maskLayer.path = maskPath.CGPath;
    sender.layer.mask = maskLayer;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.dataAr.count == 0) {
        return 0;
    }else{
    return self.dataAr.count;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YEventTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"eventCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.dataAr.count>0) {
        eventModel *eModel = self.dataAr[indexPath.row];
        cell.event.text = eModel.name;
        cell.number.text = [[NSString alloc] initWithFormat:@"%@",eModel.total ];
        if ([eModel.total integerValue] >0) {
            [cell.number setTextColor:[UIColor redColor]];
            cell.image.image = [UIImage imageNamed:@"yuan_hh"];
        }else{
            [cell.number setTextColor:[UIColor blackColor]];
            cell.image.image = [UIImage imageNamed:@"yuan_ll"];
            
        }

    }
    
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60
    ;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //self.hidesBottomBarWhenPushed = YES;
    
    YEventListTableViewController *eventLTVC =      [YEventListTableViewController new];
    eventModel *eModel = self.dataAr[indexPath.row];
    eventLTVC.typeTwo = self.typeTwo;
    eventLTVC.type = eModel.type;
    eventLTVC.site_id = eModel.site_id;
    eventLTVC.eventName = eModel.name;
    if ([eModel.total integerValue] == 0) {
        [self alertWithString:@"暂未发现存在此项安全隐患"];
    }else{
    [self showViewController:eventLTVC sender:nil];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)eventButtonAction:(UIButton *)sender {
    self.typeTwo = @"shijian";
    self.eventIma.image = [UIImage imageNamed:@"eventI"];
    self.eventNumber.hidden = YES;
    NSLog(@"%ld",(long)self.dangerNum);
    if (self.dangerNum > 0 ) {
        self.dangerNumber.hidden = NO;
    }
    
    self.dataAr = self.eventAr;
    if (self.dataAr.count>0) {
        
    
    //        冒泡排序
    for(int i = 0;i < [self.dataAr count]-1;i++){
        for(int j = i+1;j<[self.dataAr count];j++){
            eventModel *emodelI  = self.dataAr[i];
            eventModel *emodelJ = self.dataAr[j];
            int numi= [emodelI.total intValue];
            int numj= [emodelJ.total intValue];
            
            if(numi<numj) {
                //交换
                [self.dataAr exchangeObjectAtIndex:i withObjectAtIndex:j];
                
            }
        }
    }
    }
    
    [self.tableView reloadData];
}

- (IBAction)dangerButtonAction:(UIButton *)sender {
//    [sender setImage:[UIImage imageNamed:@"fengxian_hh"] forState:UIControlStateNormal];
//    self.dangerIm.image = [UIImage imageNamed:@"ss_jj_xx"];
   
    self.typeTwo = @"fengxian";
    self.eventIma.image = [UIImage imageNamed:@"dangerI"];
    if (self.eventNum > 0 ) {
        self.eventNumber.hidden = NO;
    }
    
    self.dangerNumber.hidden = YES;
    self.dataAr = self.dangerAr;
    if (self.dataAr.count > 0) {
        
    
    //        冒泡排序
    for(int i = 0;i < [self.dataAr count]-1;i++){
        for(int j = i+1;j<[self.dataAr count];j++){
            eventModel *emodelI  = self.dataAr[i];
            eventModel *emodelJ = self.dataAr[j];
            int numi= [emodelI.total intValue];
            int numj= [emodelJ.total intValue];
            
            if(numi<numj) {
                //交换
                [self.dataAr exchangeObjectAtIndex:i withObjectAtIndex:j];
                
            }
        }
    }
    }
    [self.tableView reloadData];
    
}

-(void)alertWithString:(NSString *)string{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
    }];
    [alertC addAction:otherAction];
    [self.navigationController showDetailViewController:alertC sender:nil];
    //[self.navigationController showViewController:alertC sender:nil];
    //    for (int i=0; i<self.navigationController.viewControllers.count; i++) {
    //        if ((self.navigationController.viewControllers[i] == self)) {
    //            [self.navigationController presentViewController:alertC animated:YES completion:nil];
    //        }
    //
    //    }
}

- (IBAction)zhandianxinxiButtonAction:(UIButton *)sender {
    YZhangdianxinxiViewController *zhandian = [YZhangdianxinxiViewController new];
    zhandian.webid = self.webid;
    zhandian.weburl = self.weburl;
    [self showViewController:zhandian sender:nil];
    
}
@end
